package com.qf.fmw.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtils {
    private static String className;
    private static String url;
    private static String username;
    private static String password;

    static {
        //加载配置文件
        Properties ps = new Properties();
        try {
            ps.load(DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            className = ps.getProperty("className");
            url = ps.getProperty("url");
            username = ps.getProperty("username");
            password = ps.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接对象
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(className);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeAll(AutoCloseable... cs) {
        for (AutoCloseable c : cs) {
            if (c != null) {
                try {
                    c.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
